package com.test.platform.component;

import com.test.platform.module.auto.Config;
import lombok.extern.slf4j.Slf4j;
import org.eclipse.jgit.api.Git;
import org.eclipse.jgit.lib.Ref;
import org.eclipse.jgit.transport.UsernamePasswordCredentialsProvider;
import org.springframework.context.annotation.Configuration;

import javax.annotation.Resource;
import java.io.File;
import java.util.List;

@Slf4j
@Configuration
public class GitComponent {

    @Resource(name = "autotest_config")
    private Config autotestConfig;

    /**
     * 下载自动化脚本
     * @param user 用户名 = 分支名 = 本地保存的路径地址
     * @return 是否成功
     */
    public boolean autotestScriptInit(String user) {

        log.debug("准备克隆自动化脚本到本地");

        File file = new File(autotestConfig.getScriptsGitLocat() + File.separator + user);
        log.info("仓库保存路径：{}", file.getAbsolutePath());
        if (file.exists()) {
            delete(file);
        }

        try {
            Git git = Git.cloneRepository()
                    .setCredentialsProvider(new UsernamePasswordCredentialsProvider(autotestConfig.getScriptsGitUserName(), autotestConfig.getScriptsGitPassWord()))
                    .setURI(autotestConfig.getScriptsGitUrl())
                    .setDirectory(file)
                    .call();
            git.checkout()
                    .setCreateBranch(true)
                    .setName(user)
                    .call();
            git.push().setPushAll()
                    .setCredentialsProvider(new UsernamePasswordCredentialsProvider(autotestConfig.getScriptsGitUserName(), autotestConfig.getScriptsGitPassWord()))
                    .call();
            git.close();
            log.info("克隆成功");
        } catch (Exception e) {
            log.error("克隆自动化脚本失败");
            e.printStackTrace();
            return false;
        }
        return true;
    }

    public boolean autotestScriptBranch(String branch) {

        File file = new File(autotestConfig.getScriptsGitLocat() + File.separator + branch);
        log.info("仓库保存路径：{}", file.getAbsolutePath());
        if (file.exists()) {
            delete(file);
        }

        try {
            Git git = Git.cloneRepository()
                    .setCredentialsProvider(new UsernamePasswordCredentialsProvider(autotestConfig.getScriptsGitUserName(), autotestConfig.getScriptsGitPassWord()))
                    .setURI(autotestConfig.getScriptsGitUrl())
                    .setDirectory(file)
                    .call();
            git.close();
            log.info("克隆分支成功");
        } catch (Exception e) {
            log.error("克隆分支失败");
            e.printStackTrace();
            return false;
        }
        return true;
    }

    public boolean autotestScriptPull(String user) {

        try {
            File file = new File(autotestConfig.getScriptsGitLocat() + File.separator + user);
            Git git = Git.open(file);
            git.pull()
                    .setCredentialsProvider(new UsernamePasswordCredentialsProvider(autotestConfig.getScriptsGitUserName(), autotestConfig.getScriptsGitPassWord()))
                    .call();
            git.close();
            log.info("更新成功");
        } catch (Exception e) {
            log.error("更新自动化脚本失败");
            e.printStackTrace();
            return false;
        }
        return true;
    }

    public boolean autotestScriptCommit(String user, String message) {

        try {
            File file = new File(autotestConfig.getScriptsGitLocat() + File.separator + user);
            Git git = Git.open(file);
            git.add().addFilepattern(".").call();
            git.add().setUpdate(true).addFilepattern(".").call();
            git.commit().setMessage(message).call();
            git.close();
            log.info("提交成功");
        } catch (Exception e) {
            log.error("提交自动化脚本失败");
            e.printStackTrace();
            return false;
        }
        return true;
    }

    public boolean autotestScriptPush(String user) {

        try {
            File file = new File(autotestConfig.getScriptsGitLocat() + File.separator + user);
            Git git = Git.open(file);
            git.push()
                    .setCredentialsProvider(new UsernamePasswordCredentialsProvider(autotestConfig.getScriptsGitUserName(), autotestConfig.getScriptsGitPassWord()))
                    .call();
            git.close();
            log.info("推送成功");
        } catch (Exception e) {
            log.error("推送自动化脚本失败");
            e.printStackTrace();
            return false;
        }
        return true;
    }

    public boolean autotestScriptMergeToMaster(String user) {
        // TODO autotestScriptMergeToMaster
        try {
            File file = new File(autotestConfig.getScriptsGitLocat() + File.separator + user);
            Git git = Git.open(file);
            git.close();
        } catch (Exception e) {
            log.error("推送自动化脚本失败");
            e.printStackTrace();
            return false;
        }
        return true;
    }

    private boolean branchNameExist(Git git, String branchName) {
        try {
            List<Ref> refs = git.branchList().call();
            for (Ref ref : refs) {
                if (ref.getName().contains(branchName)) {
                    return true;
                }
            }
        } catch (Exception e) {
            log.error("检查是否存在分支报错：{}", branchName);
            e.printStackTrace();
        }
        return false;
    }

    private void delete(File folder) {
        File[] files = folder.listFiles();
        for (File file : files) {
            if (file.isDirectory())
                delete(file);
            else if (file.isFile()) {
                log.info("删除：{}，成功：{}", file.getAbsolutePath(), file.delete());
            }
        }
        log.info("删除：{}，成功：{}", folder.getAbsolutePath(), folder.delete());
    }
}
